
function arrayBufferToBase64(buffer) {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);  // 将二进制字符串转为 Base64
}
async function pollTaskResult(getUrl, resultDiv, player, apiKey, maxTries = 60, interval = 3000) {
    for (let i = 0; i < maxTries; i++) {
        await new Promise(r => setTimeout(r, interval));
        try {
            const res = await fetch(getUrl, {
                headers: {
                    "Authorization": `Bearer ${apiKey}`,
                    "Content-Type": "application/json"
                }
            });

            // 增加响应内容类型验证
            const contentType = res.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                throw new Error('无效的JSON响应');
            }

            if (!res.ok) {
                throw new Error(`HTTP错误 ${res.status}`);
            }

            const data = await res.json();

            // 扩展状态判断，兼容不同API响应格式
            const status = data.status?.toLowerCase() || data.task_status;
            if (status === "success" && data.output?.file_url) {
                // resultDiv.innerHTML = "音乐生成成功！";
                // player.src = data.output?.file_url ;
                // player.style.display = "block";
                // player.load();
                resultDiv.innerHTML = "正在下载音乐";
                fetch('download', {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    }, body: JSON.stringify({ url: data.output.file_url })
                }).then(async (data) => {
                    let buf = await data.arrayBuffer();
                    console.log(buf);
                    resultDiv.innerHTML = "音乐生成成功！";
                    player.src = 'data:audio/mpeg;base64,' + arrayBufferToBase64(buf);
                    player.style.display = "block";
                    player.load();
                }).catch(e => {
                    player.style.display = "none";
                    resultDiv.innerHTML = "加载失败";
                    console.error(e);
                });
                return;
            } else if (data.status === "failure") {
                resultDiv.innerHTML = "音乐生成失败：" + (data.message || "未知错误");
                return;
            } else if (["waiting", "processing"].includes(data.status)) {
                resultDiv.innerHTML = `生成中（${i + 1}/${maxTries}次尝试）...`;
                continue; // 明确继续轮询中间状态
            }

        } catch (e) {
            // 优化错误处理
            console.error(`轮询失败 [尝试 ${i + 1}]:`, e);
            if (i === maxTries - 1) {
                resultDiv.innerHTML = `最终失败: ${e.message}`;
            }
        }
    }
    resultDiv.innerHTML = `超时（${maxTries}次尝试）`;
}

async function generateMusic() {
    const apiKey = document.getElementById('acestepApiKey').value.trim();
    const prompt = document.getElementById('musicPrompt').value.trim();
    const style = document.getElementById('musicStyle').value.trim();
    const tempo = document.getElementById('musicTempo').value.trim();
    const duration = document.getElementById('musicDuration').value.trim() || 60; // 默认60秒
    const instrument = document.getElementById('musicInstrument').value.trim();
    const resultDiv = document.getElementById('musicResult');
    const player = document.getElementById('musicPlayer');
    resultDiv.innerHTML = "正在生成音乐，请稍候...";
    player.style.display = "none";

    try {
        //▼▼▼ 构造符合Gitee AI要求的请求体 ▼▼▼
        const requestBody = {
            model: 'ACE-Step-v1-3.5B', // 模型名称
            task: 'text2music',
            duration: Number(duration),
            prompt: prompt,
            lyrics: '', // 若有歌词输入字段可补充
            reference_audio_strength: 0.5,
            infer_steps: 27,
            lora_name: 'None',
            guidance_scale: 15,
            scheduler_type: 'euler',
            cfg_type: 'apg',
            omega_scale: 10,
            seeds: [1],
            use_erg_tag: true,
            use_erg_lyric: true,
            use_erg_diffusion: true,
            // 可选参数映射
            ...(style && { edit_target_prompt: style }), // 风格映射到编辑目标提示词
            ...(instrument && { lora_name: instrument }), // 乐器映射到lora名称（根据接口文档调整）
            ...(tempo && { guidance_scale_text: Number(tempo) }) // 速度映射到文本引导系数（需确认接口字段）
        };
        //▲▲▲ 请求体构造结束 ▲▲▲

        //▼▼▼ 修改请求地址为本地后端服务 ▼▼▼
        const response = await fetch('http://localhost:3001/api/music/generate', {
            //▲▲▲ 修改结束 ▲▲▲
            method: 'POST',
            headers: {
                "Content-Type": "application/json",
                // 注意：API密钥改为通过请求体传递（由后端处理）
            },
            //▼▼▼ 调整请求体结构（符合server.js要求） ▼▼▼
            body: JSON.stringify({
                apiKey: apiKey,
                body: requestBody // 原requestBody作为body字段传递
            })
            //▲▲▲ 调整结束 ▲▲▲
        });

        const contentType = response.headers.get("content-type");
        if (!response.ok) {
            const text = await response.text();
            resultDiv.innerHTML = "请求失败：" + text;
            return;
        }
        if (contentType && contentType.includes("application/json")) {
            const data = await response.json();
            // 检查是否为异步任务
            if (data.urls && data.urls.get) {
                resultDiv.innerHTML = "音乐生成中，请稍候...";
                // 在generateMusic()函数中添加加载状态控制
                document.getElementById('loadingIndicator').style.display = 'block';
                document.getElementById('generateMusicBtn').disabled = true;

                // 在成功/失败时添加状态恢复
                document.getElementById('loadingIndicator').style.display = 'none';
                document.getElementById('generateMusicBtn').disabled = false;

                // 添加下载功能
                document.getElementById('downloadBtn').addEventListener('click', function () {
                    const audioSrc = document.getElementById('musicPlayer').src;
                    if (audioSrc) {
                        const a = document.createElement('a');
                        a.href = audioSrc;
                        a.download = '生成的音乐.mp3';
                        a.click();
                    }
                });
                pollTaskResult(data.urls.get, resultDiv, player, apiKey);
            } else if (data.output?.file_url) {
                resultDiv.innerHTML = "音乐生成成功！";
                player.src = data.output?.file_url;
                player.style.display = "block";
                player.load();
            } else {
                resultDiv.innerHTML = "音乐生成失败：" + (data.message || "未知错误");
            }
        } else {
            const text = await response.text();
            resultDiv.innerHTML = "返回内容不是JSON：" + text;
        }
    } catch (e) {
        resultDiv.innerHTML = "请求出错：" + e.message;
    }
}